package com.cleanvegetable.service.dingtalk;

import com.dingtalk.api.DefaultDingTalkClient;
import com.dingtalk.api.DingTalkClient;
import com.dingtalk.api.request.OapiGettokenRequest;
import com.dingtalk.api.request.OapiV2DepartmentListsubRequest;
import com.dingtalk.api.response.OapiGettokenResponse;
import com.dingtalk.api.response.OapiV2DepartmentListsubResponse;
import com.taobao.api.ApiException;
import com.cleanvegetable.common.config.DingTalkConfig;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.List;

/**
 * 钉钉服务类
 * 提供钉钉开放平台API的调用服务
 *
 * @author cleanvegetable
 * @date 2024/02/24
 */
@Slf4j
@Service
public class DingTalkService {

    @Resource
    private DingTalkConfig dingTalkConfig;

    /**
     * 获取访问令牌
     * 用于后续API调用的身份验证
     *
     * @return 访问令牌
     */
    public String getAccessToken() {
        try {
            log.info("开始获取钉钉访问令牌，appKey={}", dingTalkConfig.getAppKey());
            
            // 创建客户端实例
            DingTalkClient client = new DefaultDingTalkClient("https://oapi.dingtalk.com/gettoken");
            
            // 创建请求对象
            OapiGettokenRequest req = new OapiGettokenRequest();
            req.setAppkey(dingTalkConfig.getAppKey());
            req.setAppsecret(dingTalkConfig.getAppSecret());
            req.setHttpMethod("GET");
            
            // 发送请求并获取响应
            OapiGettokenResponse response = client.execute(req);
            
            // 检查响应是否成功
            if (response.isSuccess()) {
                log.info("获取钉钉访问令牌成功");
                return response.getAccessToken();
            } else {
                log.error("获取钉钉访问令牌失败：errcode={}, errmsg={}", response.getErrcode(), response.getErrmsg());
                throw new RuntimeException("获取钉钉访问令牌失败：" + response.getErrmsg());
            }
        } catch (ApiException e) {
            log.error("获取钉钉访问令牌失败", e);
            throw new RuntimeException("获取钉钉访问令牌失败", e);
        }
    }

    /**
     * 获取部门列表
     * 获取企业部门列表，支持分页查询
     *
     * @param deptId 部门ID，根部门传1
     * @param language 通讯录语言：zh_CN（默认）、en_US
     * @return 部门列表
     */
    public List<OapiV2DepartmentListsubResponse.DeptBaseResponse> getDepartmentList(Long deptId, String language) {
        try {
            // 获取访问令牌
            String accessToken = getAccessToken();
            log.info("获取到访问令牌：{}", accessToken);
            
            // 创建客户端实例
            DingTalkClient client = new DefaultDingTalkClient("https://oapi.dingtalk.com/topapi/v2/department/listsub");
            
            // 创建请求对象
            OapiV2DepartmentListsubRequest req = new OapiV2DepartmentListsubRequest();
            // 设置请求参数
            req.setDeptId(deptId);
            req.setLanguage(language);
            req.setHttpMethod("POST");
            
            // 发送请求并获取响应
            OapiV2DepartmentListsubResponse response = client.execute(req, accessToken);
            
            // 检查响应是否成功
            if (response.isSuccess()) {
                log.info("获取部门列表成功，部门数量：{}", response.getResult().size());
                return response.getResult();
            } else {
                log.error("获取部门列表失败：errcode={}, errmsg={}", response.getErrcode(), response.getErrmsg());
                throw new RuntimeException("获取部门列表失败：" + response.getErrmsg());
            }
        } catch (ApiException e) {
            log.error("获取部门列表失败", e);
            throw new RuntimeException("获取部门列表失败", e);
        }
    }

    /**
     * 发送工作通知消息
     *
     * @param userIds 接收者的用户ID列表
     * @param content 消息内容
     */
    public void sendWorkNotification(String[] userIds, String content) {
        try {
            // TODO: 实现发送工作通知的逻辑
            log.info("开始发送工作通知消息，接收者：{}，内容：{}", String.join(",", userIds), content);
        } catch (Exception e) {
            log.error("发送工作通知消息失败", e);
            throw new RuntimeException("发送工作通知消息失败", e);
        }
    }

    /**
     * 发送群机器人消息
     *
     * @param content 消息内容
     */
    public void sendRobotMessage(String content) {
        try {
            // TODO: 实现发送群机器人消息的逻辑
            log.info("开始发送群机器人消息，内容：{}", content);
        } catch (Exception e) {
            log.error("发送群机器人消息失败", e);
            throw new RuntimeException("发送群机器人消息失败", e);
        }
    }

    /**
     * 获取部门用户列表
     *
     * @param deptId 部门ID
     * @return 用户列表
     */
    public Object getDepartmentUserList(Long deptId) {
        try {
            // TODO: 实现获取部门用户列表的逻辑
            log.info("开始获取部门用户列表，部门ID：{}", deptId);
            return null;
        } catch (Exception e) {
            log.error("获取部门用户列表失败", e);
            throw new RuntimeException("获取部门用户列表失败", e);
        }
    }
} 